import Axios from 'axios';
import Vue from 'vue';

export default class codePush {
  constructor() {
    this.vm = new Vue();
  }

  update({ url, name }) {
    if (window.plus) {
      this.getAppVersion(url).then((res) => {
        const result = res.data;
        let version = null;

        window.plus.runtime.getProperty(window.plus.runtime.appid, (data) => {
          version = data.version;

          if (data.forceUpdate) {
            this.download(result.url);
          } else if (version !== result.version && name === result.name) {
            this.download(result.url);
          }

          if (data.cleanStorage) {
            window.localStorage.clear();
            window.sessionStorage.clear();
          }
        });
      });
    }
  }

  async getAppVersion(url) {
    return Axios.get(url).then((res) => {
      return res;
    });
  }

  download(url = '') {
    this.vm.$toast.loading({
      mask: true,
      message: 'APP更新中...',
      duration: 0,
    });

    window.plus.downloader
      .createDownload(url, { filename: '_doc/update/' }, (d, status) => {
        if (status === 200) {
          this.install(d.filename);
        } else {
          this.vm.$toast.clear();
          this.vm.$dialog.alert({
            message: '下载安装包失败！',
          });
        }
      })
      .start();
  }

  install(path) {
    this.vm.$toast.loading({
      mask: true,
      message: 'APP安装中...',
      duration: 0,
    });

    window.plus.runtime.install(
      path,
      {},
      () => {
        this.vm.$dialog
          .alert({
            message: '应用资源更新完成,点击重启',
          })
          .then(() => {
            window.plus.runtime.restart();
          });
      },
      (e) => {
        this.vm.$toast.clear();
        this.vm.$dialog.alert({
          message: `安装失败[${e.code}]：${e.message}`,
        });
      },
    );
  }
}
